{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 本质：统计每个像素灰度 出现的概率 0-255 p\n",
    "# 累计概率 \n",
    "# 1 0.2  0.2\n",
    "# 2 0.3  0.5\n",
    "# 3 0.1  0.6\n",
    "# 256 \n",
    "# 100 0.5 255*0.5 = new \n",
    "import cv2\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "img = cv2.imread('image0.jpg',1)\n",
    "\n",
    "\n",
    "imgInfo = img.shape\n",
    "height = imgInfo[0]\n",
    "width = imgInfo[1]\n",
    "gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n",
    "cv2.imshow('src',gray)\n",
    "count = np.zeros(256,np.float)\n",
    "for i in range(0,height):\n",
    "    for j in range(0,width):\n",
    "        pixel = gray[i,j]\n",
    "        index = int(pixel)\n",
    "        count[index] = count[index]+1\n",
    "for i in range(0,255):\n",
    "    count[i] = count[i]/(height*width)\n",
    "#计算累计概率\n",
    "sum1 = float(0)\n",
    "for i in range(0,256):\n",
    "    sum1 = sum1+count[i]\n",
    "    count[i] = sum1\n",
    "#print(count)\n",
    "# 计算映射表\n",
    "map1 = np.zeros(256,np.uint16)\n",
    "for i in range(0,256):\n",
    "    map1[i] = np.uint16(count[i]*255)\n",
    "# 映射\n",
    "for i in range(0,height):\n",
    "    for j in range(0,width):\n",
    "        pixel = gray[i,j]\n",
    "        gray[i,j] = map1[pixel]\n",
    "cv2.imshow('dst',gray)\n",
    "cv2.waitKey(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
